package io.demo.message.domain.proto;

import com.google.protobuf.Message;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

class MessageConverterRegistry {

  private Map<Class<?>, MessageConverter<?, ? extends Message>> registry;

  private MessageConverterRegistry() {
    registry = new ConcurrentHashMap<>();
  }

  private <B, M extends Message> MessageConverterRegistry(
      Map<Class<B>, MessageConverter<B, M>> registry) {
    this.registry = new ConcurrentHashMap<>();
    registry.forEach((k, v) -> this.registry.put(k, v));
  }

  static MessageConverterRegistry empty() {
    return new MessageConverterRegistry();
  }

  static <B, M extends Message> MessageConverterRegistry from(
      Map<Class<B>, MessageConverter<B, M>> bmMap) {
    return new MessageConverterRegistry(bmMap);
  }

  <B, M extends Message> MessageConverterRegistry register(
      Class<B> clazz, MessageConverter<B, M> entry) {
    registry.put(clazz, entry);
    return this;
  }

  <B> MessageConverterRegistry unregister(Class<B> bClass) {
    registry.remove(bClass);
    return this;
  }

  public <B, M extends Message> MessageConverter<B, M> get(Class<B> bClass) {
    @SuppressWarnings("unchecked")
    MessageConverter<B, M> converter = (MessageConverter<B, M>) registry.get(bClass);
    return converter;
  }

  boolean isEmpty() {
    return registry.isEmpty();
  }

  int size() {
    return registry.size();
  }
}
